<?php

namespace Axe\Http\Controllers;

use Axe\Models\Admin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

abstract class AuthController extends BaseController
{
    protected $viewGroup;

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $paginate = $this->getModel()->newQuery()->paginate();

        return $this->vendorView($this->viewGroup.'.index', [
            'list' => $paginate,
        ]);
    }

    /**
     * @return Model
     */
    abstract public function getModel(): Model;

    protected function vendorView($view, $data = [], $mergeData = [])
    {
        return parent::vendorView($view, $data, $mergeData); // TODO: Change the autogenerated stub
    }

    /**
     * @return Admin
     */
    public function getAdmin()
    {
        return request()->attributes->get('admin');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return $this->vendorView($this->viewGroup.'.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $model = $this->getModel();
        $model->fill($request->only($model->getFillable()))->save();

        return $this->vendorJson($model->exists, null, '创建成功');
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     *
     * @return Response
     */
    public function show($id)
    {
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $model = $this->getModel()->findOrFail($id);

        return $this->vendorView($this->viewGroup.'.edit', [
            'data' => $model,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param int     $id
     *
     * @return Response
     */
    public function update(Request $request, $id)
    {
        $model = $this->getModel()->findOrFail($id);
        $model->fill($request->only($model->getFillable()))->save();

        return $this->vendorJson($model->exists, null, '修改成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $model = $this->getModel()->findOrFail($id);
        if ($model) {
            $model->delete();

            return $this->vendorJson(true, $model, '操作完成');
        }

        return $this->vendorJson(false, $model, '删除失败');
    }
}
